package com.zmn.oms.api.controller.ins;

import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.model.dto.ins.InsOrderMasterCpicDTO;
import com.zmn.oms.model.entity.ins.InsOrderMasterCpic;
import com.zmn.oms.services.interfaces.ins.InsOrderMasterCpicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @author lhl
 * @date 2021/03/26 10:12
 */
@Slf4j
@RestController
@RequestMapping("ins/cpic/")
public class CpicInsController {

    @Autowired
    private InsOrderMasterCpicService insOrderMasterCpicService;

    @ResponseBody
    @RequestMapping("pushInsureds")
    public String pushInsureds(@RequestBody Map params) {
        log.info("收到按单保险师傅保单数据：[{}]", params);

        List list = Optional.ofNullable(params)
                .map(map -> map.get("body"))
                .map(obj -> (obj instanceof Map) ? (Map) obj : null)
                .map(body -> body.get("insuredList"))
                .map(obj -> (obj instanceof List) ? (List) obj : null)
                .get();

        if (list == null || list.isEmpty()) {
            return "ok";
        }

        List<InsOrderMasterCpic> masterCpics = new LinkedList<>();
        for (Object item : list) {
            InsOrderMasterCpicDTO dto = BeanMapper.map(item, InsOrderMasterCpicDTO.class);
            if (dto.getFormStatus() == null) {
                continue; // 没有出单状态，忽略
            }
            if (dto.getExtAttr() == null || !Pattern.matches("^\\d+$", dto.getExtAttr()) ) {
                continue; // 没有insMasterId,无法匹配数据，忽略
            }

            InsOrderMasterCpic model = new InsOrderMasterCpic();
            model.setInsMasterId(Long.parseLong(dto.getExtAttr()));
            model.setFormStatus(dto.getFormStatus());
            if (StringUtil.isNotBlank(dto.getInsureNo())) {
                model.setInsureNo(dto.getInsureNo());
                model.setErpSyncFlag(InsOrderMasterCpic.ERP_SYNC_FLAG_NEED);
            }
            if (StringUtil.isNotBlank(dto.getMsg())) {
                model.setMsg(dto.getMsg());
            }
            masterCpics.add(model);
        }

        if (!masterCpics.isEmpty()) {
            for (InsOrderMasterCpic item : masterCpics) {
                insOrderMasterCpicService.updateByKey(item);
            }
        }

        return "ok";
    }

    @ResponseBody
    @RequestMapping("sync")
    public Map sync() {
        log.info("CpicInsController.sync() is called!");

        Map<String, String> map = new HashMap();
        map.put("status", "001");
        map.put("errmsg", "成功");
        return map;
    }
}
